package com.ehl.capture.data;

import com.alibaba.fastjson.JSONArray;
import com.ehl.capture.bean.CarBean;
import com.ehl.capture.db.Config;
import com.ehl.capture.db.DBProxyZdkk;
import com.ehl.capture.db.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @author Jiax
 * @version 1.0.0
 * @description: ZdkkCheck
 * @date 2024-05-18 14:14
 */
public class ZdkkService {
    private static final boolean ZDDD_OUT_LOG = Boolean.parseBoolean(Config.getValue("zdkk.redischeck.outlog"));
    private static Logger logger = Logger.getLogger(ZdkkService.class);
    /**
     *  发送前判断下是否有超时，
     * (1)如果是重点卡口，直接写redis,如果它还是超时的，则移除超时
     * (2)如果当前卡口不是重点卡口，恰好重点卡口中又有超时的卡口，将这个普通卡口变成重点卡口编号，然后超时中移除，添加redis
     * @param bean
     */
    public static void chekcZdkkOverTime(CarBean bean) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getJedis();
            List<String> zdkkList = DBProxyZdkk.getKkList();
            List<String> kkOverTimeList = DBProxyZdkk.getKkOverTimeList();
            String kkbh = bean.getKkbh();
            if(ZDDD_OUT_LOG){
                logger.info("zdkkList设置了" + JSONArray.toJSONString(zdkkList) + "个,kkOverTimeList有" + JSONArray.toJSONString(kkOverTimeList)+ "个,当前卡口编号：" + kkbh);
            }

            if(zdkkList.contains(kkbh)){
                if(ZDDD_OUT_LOG){
                    logger.info("这是一个重点卡口：" + kkbh);
                }
                // 是重点卡口，写redis,如果它还是超时的，则移除超时
                jedis.setex(kkbh,RedisUtil.getPeriod(), com.ehl.capture.tool.DateUtils.getNowTime());
                if(ZDDD_OUT_LOG){
                    logger.info("Redis写入了卡口编号" + kkbh);
                }
                if(kkOverTimeList.contains(kkbh)){
                    kkOverTimeList.remove(kkbh);
                }
            }else {
                // 不是重点卡口,但是重点卡口有超时的,将这个普通卡口变成重点卡口编号，然后超时中移除，添加redis
                if(CollectionUtils.isNotEmpty(kkOverTimeList)){
                    String zdkkBh = kkOverTimeList.get(0);
                    if(ZDDD_OUT_LOG){
                        logger.info("这不是一个重点卡口：" + kkbh + ";重点卡口是：" + zdkkBh);
                    }
                    bean.setKkbh(zdkkBh);
                    jedis.setex(zdkkBh,RedisUtil.getPeriod(), com.ehl.capture.tool.DateUtils.getNowTime());
                    if(ZDDD_OUT_LOG){
                        logger.info("Redis写入了卡口编号" + zdkkBh);
                    }
                    kkOverTimeList.remove(zdkkBh);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            RedisUtil.closeJedis(jedis);
        }

    }
}
